<?php

class Database
{
    private $pdo;
    private $inTransaction = false;

    public function __construct($host, $dbname, $user, $password)
    {
        $this->pdo = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $user, $password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function query($sql, $params = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

//    批量插入数据
    public function batchInsert($table, $data)
    {
        if (empty($data)) {
            return;
        }

        $columns = implode(', ', array_keys($data[0]));
        $placeholders = ':' . implode(', :', array_keys($data[0]));

        $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)";
        echo $sql;
        // 准备SQL语句
        $stmt = $this->pdo->prepare($sql);

        // 绑定参数并执行
        foreach ($data as $index => $row) {
            foreach ($row as $key => $value) {
                $paramName = ":" . $key . ($index + 1);
                echo $paramName.' '.$value.PHP_EOL;
                $stmt->bindValue($paramName, $value);
            }
        }
        return $stmt->execute();
    }

    public function beginTransaction()
    {
        if (!$this->inTransaction) {
            $this->pdo->beginTransaction();
            $this->inTransaction = true;
        }
    }

    public function commit()
    {
        if ($this->inTransaction) {
            $this->pdo->commit();
            $this->inTransaction = false;
        }
    }

    public function rollBack()
    {
        if ($this->inTransaction) {
            $this->pdo->rollBack();
            $this->inTransaction = false;
        }
    }
}
